<?php
include('../../include/functions.inc.php');
$user = unserialize($_SESSION['user']);
$fac = $_SESSION["factura"];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Asignacion de Estudiantes</title>
        <link href="../../bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css" />
        <link href="../../css/ContentStyle.css" rel="stylesheet" type="text/css" />
        <link href="../../css/tableorderer.css" rel="stylesheet" type="text/css" />
        <link href="../../js/dialog/dialog.2.0.css" rel="stylesheet" type="text/css" />
        <link href="../../js/protocalendar/datepicker.css" rel="stylesheet" type="text/css" />
        <script src="../../js/jquery.js" type="text/javascript"></script>
        <script>jQuery.noConflict();</script>
        <script src="../../bootstrap/js/bootstrap.js"></script>
        <script src="../../js/prototype.js" type="text/javascript"></script>
        <script src="../../js/jsvalidate.js" type="text/javascript"></script>
        <script src="../../js/TableOrderer.js" type="text/javascript"></script>
        <script src="../../js/dialog/dialog.2.0.js" type="text/javascript"></script>
        <script src="../../js/include.js" type="text/javascript"></script>
        <script src="../../js/protocalendar/prototype-date-extensions.js" type="text/javascript"></script>
        <script src="../../js/protocalendar/datepicker.js"  type="text/javascript"></script>
        <style type="text/css">
            input,
            textarea{
                width: 300px;
            }
            select{
                width: 314px;
            }
        </style>
        <script type="text/javascript">
            var cargos = new Hash();
            var cargos1 = new Hash();
            cleanComa = function(str) {
                n = str.split(",");

                newStr = "";
                var i = 0;
                for (i = 0; i < n.length; i++) {
                    newStr = newStr + n[i];
                }
                return newStr;
            };

            var selected = null;
            setCargo1 = function() {
                var cargo1 = new Hash({
                    ID: $F("CD"),
                    NOMBRE: $F("CARGO1"),
                    MONTO: parseFloat(cleanComa($F("MONTO"))),
                    MORA: parseFloat(cleanComa($F("MORA")))
                });
                cargo1 = cargo1.toObject();
                cargos1.set(cargo1.ID, cargo1);
                refreshTable1();
                selected = null;
                sumCargos();
                $("ITEM1").reset();
            };

            refreshTable1 = function() {
                new TableOrderer("detalle1", {data: cargos1.values(),
                    filter: 'top', callBack: loadCargo1});
            };

            loadCargo1 = function(s) {
                $("CARGO1").value = s.NOMBRE;
                $("MONTO").value = cleanComa(s.MONTO);
                $("MORA").value = cleanComa(s.MORA);
                $("CD").value = s.ID;
                $("FECHAPAGO").value = s.FECHA_PAGO;
                $("MONEDA").value = s.MONEDA;
            };

            delCargo1 = function() {
                cargos1.unset($F("CD"));
                sumCargos();
                refreshTable1();
                $("ITEM1").reset();
            };

            setCargo = function() {
                if ($F("CANTIDAD") === 0) {
                    Dialogs.alert("Debe ingresar un cantidad e Items");
                    return;
                }

                var cargo = new Hash({ID: $F("ID"), DESCRIPCION: $F("CARGO"),
                    CANTIDAD: $F("CANTIDAD"), PRECIO: $F("PRECIO"),
                    SUBTOTAL: (parseFloat($F("CANTIDAD")) * parseFloat(cleanComa($F("PRECIO"))))});
                cargo = cargo.toObject();
                cargos.set(cargo.ID, cargo);
                refreshTable();
                sumCargos();
                $("ITEM").reset();
            };

            refreshTable = function() {
                new TableOrderer("detalle", {data: cargos.values(),
                    filter: 'top', callBack: loadCargo});
            };

            loadCargo = function(s) {
                $("CARGO").value = s.DESCRIPCION;
                $("PRECIO").value = s.PRECIO;
                $("CANTIDAD").value = s.CANTIDAD;
                $("ID").value = s.ID;
            };

            delCargo = function() {
                if (!$F("ID").empty()) {
                    if (cargos.toArray().length > 0) {
                        cargos.unset($F("ID"));
                    }
                    sumCargos();
                    refreshTable();
                } else {
                    Dialogs.alert("Debe seleccionar un Item de la factura");
                }
            };

            sumCargos = function() {
                var monto = 0;
                cargos.each(function(i) {
                    monto += parseFloat(i.value.SUBTOTAL);
                });
                cargos1.each(function(i) {
                    monto += parseFloat(i.value.ABONO_REAL);
                });
                /*cargos1.each(function(i){
                 monto+=parseFloat(i.value.MONTO);
                 monto+=parseFloat(i.value.MORA);
                 }); */
                $('TOTAL').value = parseFloat(monto);
                $('IVA').value = parseFloat(monto) * 0.12;
            };

            var rsv;
            config = function() {
                rsv = new RSV({
                    formID: $(document.FACTURA),
                    errorFieldClass: "errorField",
                    rules: ["required,NIT,NIT Es requerido!",
                        "required,NOMBRE,Nombre de Factura es Requerido!",
                        "required,DIR,Ingrese una direccion para la Factura!",
                        "required,STATUS,Seleccione el estad de la Factura!"],
                    displayType: "display-html",
                    errorHTMLItemBullet: "&#8212; ",
                    onCompleteHandler: function() {
                        if (cargos.values().length === 0 && cargos1.values().length === 0) {
                            Dialogs.alert('No puede guardar una factura sin detalle!');
                        } else {
                            $('operation').value = 'save';
                            $('json').value = JSON.stringify(cargos.values());
                            $('json1').value = JSON.stringify(cargos1.values());

                            waitMsg("Guardando...");
                            $(document.FACTURA).submit();
                        }
                    }
                });
            };
            addOnLoad(config);

            selCargo = function(s) {
                $("CARGO").value = s.NOMBRE;
                $("PRECIO").value = s.PRECIO;
                $("CANTIDAD").value = 1;
                $("ID").value = s.ID;
                closeWait();
            };

            showCargos = function() {
                var f = new Hash({tittle: 'Cargos Facturacion', width: 500, height: 500, url: 'data.php?operation=cargos', callback: selCargo});
                setList(null, f.toObject());
            };

            selCargo1 = function(s) {
                selected = s;
                $("CARGO1").value = s.NOMBRE;
                $("MONTO").value = s.MONTO;
                $("MORA").value = s.MORA;
                $("CD").value = s.ID;
                closeWait();
            };

            showCargos1 = function() {
                var f = new Hash({tittle: 'Cargos Facturacion', width: 500, height: 500, url: 'data.php?operation=cargos1', callback: selCargo1});
                setList(null, f.toObject());
            };

            showStud = function() {
                var f = new Hash({tittle: 'Listado de Estudiantes', url: 'studentList.php', callback: selEstud, width: 800, height: 500});
                setList(null, f.toObject());
            };

            selEstud = function(s) {
                $("NIT").value = s.NIT;
                $("NOMBRE").value = s.NOMBRE_FACTURA;
                $("DIR").value = s.DIRECCION;
                $("TOTAL").value = 0.00;
                jQuery("#detalle").html("");
                arrSplit = s.ID.split('_');
                $("STUDENT").value = arrSplit[0];
                $("ACCOUNT").value = arrSplit[1];
                loadCargos();
                cargos = new Hash();
                cargos1 = new Hash();
            };
            /*Nuevo*/
            var moneda = null;
            loadCargos = function() {
                $('divCargos').innerHTML = 'Cargando...';
                var a = new Ajax.Updater('divCargos', '../payments/payments.php', {
                    method: 'get',
                    parameters: Form.serialize($(document.FACTURA)),
                    onComplete: function(r) {
                        $('divCargos').update(r.responseText);
                        //$('refresh').disabled=false;
                    }
                });
            };

            doit = function(c, d) {
                d.checked = c.checked;
                txt = "txt_" + d.ID;
                $(txt).readOnly = !c.checked;
                if (c.checked) {
                    /*moneda=moneda==null?d.MONEDA:moneda;
                     if(d.MONEDA!=moneda){
                     alert("Solo puede seleccionar cargos con la misma moneda!");
                     c.checked=false;
                     }
                     else {*/
                    d.ABONO = d.TOT;
                    if (d.MONEDA == 2) {
                        d.ABONO_REAL = d.TOT * $("TASA").value;
                    }
                    else {
                        d.ABONO_REAL = d.TOT;
                    }
                    setCargo1(d);
                    //console.log(d);
                    sumCargos();
                    //}
                }
                else {
                    delCargo1(d);
                }
            }

            setCargo1 = function(cargo) {
                cargos1.set(cargo.ID, cargo);
            }

            delCargo1 = function(cargo) {
                cargos1.unset(cargo.ID);
                sumCargos();
                txt = $("txt_" + cargo.ID)
                txt.className = "";
                txt.value = parseFloat(cargo.TOT);

                if (cargos1.values().size() == 0) {
                    moneda = null;
                }
            }

            setAbono = function(c, idObj) {
                var d = cargos1.get(idObj);
                if ((c.value * 1) > (d.TOT * 1)) {
                    Dialogs.close();
                    Dialogs.alert("El abono debe ser igual o menor al cargo");
                    c.className = "errorField";
                    c.focus();
                    return;
                }
                c.className = "";
                d.ABONO = c.value;
                if (d.MONEDA == 2) {
                    d.ABONO_REAL = c.value * $("TASA").value;
                    if (c.value > d.PENAL_REF) {
                        d.PENAL = d.PENAL_REF;
                    }
                    else {
                        d.PENAL = 0;
                    }
                }
                else {
                    d.ABONO_REAL = c.value;
                }
                setCargo1(d);
                //console.log(d);
                sumCargos();
            }

            calcularTotalPagar = function() {
                cargos1.each(function(i) {
                    //console.log(i);
                    var d = cargos1.get(i.key);
                    if (d.MONEDA == 2) {
                        d.ABONO_REAL = d.ABONO * $("TASA").value;
                        setCargo1(d);
                    }
                });
                sumCargos();
            }
        </script>
    </head>
    <body>
        <div id="tabs">
            <ul class="nav nav-tabs">
                <li class="active">
                    <a>Facturación</a>
                </li>
            </ul>
        </div>
        <div id="tabs-cont">
            <div id="rsvErrors"></div>
            <form id="FACTURA" name="FACTURA" method="GET" action="data.php">
                <table width="100%" border="0" cellpadding="0" cellspacing="0" class="">
                    <tr>
                        <th width="50%">
                            &nbsp;
                        </th>
                        <th width="50%" valign="middle">
                            <input type="button" name="cmdOk" class="btn btn-info" id="cmdOk" value="Continuar" onclick="rsv.validate();" />
                        </th>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <br/>
                            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                <tr>
                                    <td width="20%">FACTURA</td>
                                    <td width="80%">

                                        <input style="width:145px" name="SERIE" type="text" id="SERIE" value="<?php echo $fac["SERIE"] ?>" size="10" readonly="readonly" />
                                        <input style="width:137px" name="NUMERO" type="text" id="NUMERO" size="10" readonly="readonly" value="?" /></td>
                                </tr>
                                <tr>
                                    <td>NIT</td>
                                    <td>
                                        <input name="STUDENT" type="hidden" id="STUDENT"/>
                                        <input name="ACCOUNT" type="hidden" id="ACCOUNT"/>
                                        <input name="NIT" type="text" id="NIT"/>&nbsp;<input name="buscard" onclick="showStud()" type="button" class="btn btn-small" id="buscar"  value="..." />
                                    </td>
                                </tr>

                                <tr>
                                    <td>NOMBRE</td>
                                    <td><input name="NOMBRE" type="text" id="NOMBRE" size="50" /></td>
                                </tr>
                                <tr>
                                    <td>DIRECCION</td>
                                    <td>
                                        <input name="DIR" type="text" id="DIR" size="50" />
                                        <input type="hidden" name="operation" id="operation" />
                                        <input type="hidden" name="json" id="json" />
                                        <input type="hidden" name="json1" id="json1" />
                                    </td>
                                </tr>
                                <tr>
                                    <td>TASA CAMBIO</td>
                                    <td><input name="TASA" type="text" id="TASA" size="25" value="8" onchange="calcularTotalPagar();" /></td>
                                </tr>
                                <tr>
                                    <td>TOTAL A FACTURAR</td>
                                    <td><input name="TOTAL" type="text" id="TOTAL" size="25" readonly="readonly" /></td>
                                </tr>
                                <tr>
                                    <td>FECHA FACTURACION</td>
                                    <td>
                                        <input name="FECHAPAGO" value="<?php echo date("Y-m-d"); ?>" 
                                               readonly="readonly" type="text" id="FECHAPAGO" size="30" />
                                        <script type="text/javascript">
            new Control.DatePicker('FECHAPAGO', {locale: 'es', icon: '../../js/protocalendar/calendar.png', dateFormat: 'yyyy-MM-dd'});
                                        </script>
                                    </td>
                                </tr>
                                <tr>
                                    <td>IVA </td>
                                    <td><input name="IVA" type="text" id="IVA" size="25" value="" readonly="readonly" /></td>
                                </tr>

                                <tr>
                                    <td>ESTADO FACTURA</td>
                                    <td>
                                        <select name="STATUS" id="STATUS">
                                            <option value="1">PAGADA</option>
                                            <option value="2">EN TRAMITE</option>
                                            <option value="" selected="selected">Seleccionar</option>
                                        </select>
                                    </td>
                                </tr>
                            </table></td>
                    </tr>
                </table>


            </form>
            <table width="100%" cellpadding="0" cellspacing="0" class="">
                <tr>
                    <th width="40%"><legend>Nuevo Item</legend></th>
                    <th width="60%"><legend>Detalle Item</legend></th>
                </tr>
                <tr>
                    <td> 
                        <form id="ITEM" name="ITEM" method="post" action="">
                            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                <tr>
                                    <td width="25%">CARGO</td>
                                    <td width="75%">
                                        <input name="CARGO" type="text" id="CARGO" size="50" readonly="readonly" />
                                        <input type="button" name="buscar" id="buscar" onclick="showCargos();" value="..." class="btn btn-small"/>
                                    </td>
                                </tr>
                                <tr>
                                    <td>PRECIO</td>
                                    <td><input name="PRECIO" type="text" id="PRECIO" readonly="readonly" size="25" /></td>
                                </tr>
                                <tr>
                                    <td>CANTIDAD</td>
                                    <td>
                                        <input style="width:50px" name="CANTIDAD" type="text" id="CANTIDAD" value="1" size="25" />
                                        <input type="hidden" name="ID" id="ID" />
                                    </td>
                                </tr>
                                <tr>
                                    <td>&nbsp;</td>
                                    <td>
                                        <div class="btn-group">
                                            <input type="button" class="btn btn-info"  name="cmdOk2" id="cmdOk2" value="Agregar" onclick="setCargo()" />
                                            <input type="button" class="btn btn-info"  name="cmdOk3" id="cmdOk3" value="Borrar" onclick="delCargo()" />
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </form>
                    </td>
                    <td><div id="detalle"></div></td>
                </tr>
                <!--<tr>
                    <th colspan="2">Detalle Item</th>
                </tr>
                <tr>
                    <td colspan="2"><div id="detalle"></div></td>
                </tr>-->
                <tr>
                    <th colspan="2"><legend>Pagos pendientes</legend></th>
                </tr>
                <tr>
                    <table class="table table-striped">
                        <td colspan="2"><div id="divCargos"></div></td>
                </tr>
            </table>            
        </div>
    </body>
</html>
